package com.mo;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.LineHandler;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class TdkExtractorDemo {

    static String[] userIds = new String[]{"1683343567792", "1683340029012", "1683343652521", "1683343661418", "1683343679896"};
    static Random random = new Random();

    public static void main(String[] args) throws Exception {
        String pathname = "C:\\Users\\moon.pan\\Desktop\\landing_page.csv";
        FileInputStream inputStream = new FileInputStream(pathname);
        IoUtil.readUtf8Lines(inputStream, (LineHandler) line -> {
            ThreadUtil.sleep(1000);
            String[] domains = line.split(",");
            String domain = domains[0];
            System.out.println(StrUtil.format("\"{}\",\"{}\",\"{}\"", domain, domains[1], promptApiHub(domain)));
        });
        IoUtil.close(inputStream);
    }

    public static String promptChat(String domain) {
        try {
            Map<String, Object> body = new HashMap<>();
            body.put("prompt", StrUtil.format("搜索一下'{}'这个网站是做什么的", domain));
            body.put("userId", StrUtil.format("#/chat/{}", userIds[random.nextInt(userIds.length)]));
            body.put("network", true);
            body.put("system", "");
            body.put("withoutContext", false);
            body.put("stream", false);

            HttpResponse response = HttpUtil.createPost("https://api.binjie.fun/api/generateStream")
                    .header("Origin", "https://chat.jinshutuan.com")
                    .body(JSONUtil.toJsonStr(body))
                    .execute();
            if (response.isOk()) {
                String responseBody = response.body();
                return responseBody.replace("\n", ";").replace("\r", ";");
            }
        } catch (Exception e) {

        }
        return null;
    }


    public static String promptApiHub(String domain) {
        String url = "http://api-sgp.eclicktech.com.cn/gst/aichat/api/v1/open/chat/completion";
        StringBuilder result = new StringBuilder();
        try {

            Map<String, Object> body = new HashMap<>();
            body.put("conversation_id", IdUtil.simpleUUID());
            body.put("content", StrUtil.format("搜索一下'{}'这个网站是做什么的", domain));
//
//            HttpResponse response = HttpUtil.createPost("http://api-sgp.eclicktech.com.cn/gst/aichat/api/v1/open/chat/completion")
//                    .header("x-apihub-env", "prod")
//                    .header("x-apihub-ak", "79176b9be96748c6926ad17fe6fee7ea")
//                    .body(JSONUtil.toJsonStr(body))
//                    .execute();
//            if (response.isOk()) {
//                String responseBody = response.body();
//                return responseBody.replace("\n", ";").replace("\r", ";");
//            }

            HttpPost request = new HttpPost(url);
            request.setHeader("content-type", "application/json");
            request.setHeader("Host", "api-sgp.eclicktech.com.cn");
            request.setHeader("Accept", "text/event-stream");
            request.addHeader("x-apihub-env", "prod");
            request.addHeader("x-apihub-ak", "79176b9be96748c6926ad17fe6fee7ea");
            request.setEntity(new StringEntity(JSONUtil.toJsonStr(body), ContentType.APPLICATION_JSON));

            CloseableHttpClient client = HttpClientBuilder.create().build();
            CloseableHttpResponse response = client.execute(request);

            HttpEntity entity = response.getEntity();
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));

            String line;
            while ((line = reader.readLine()) != null) {

                if (StrUtil.isNotEmpty(line) && line.startsWith("data:")) {
                    String message = line.substring(line.indexOf(":") + 1).trim();
                    String content = JSONUtil.parseObj(message).getStr("content");
                    result.append(content);
                }
            }

            EntityUtils.consume(entity);
            IoUtil.close(response);
            IoUtil.close(client);
        } catch (Exception e) {

        }
        return result.toString().replace("\n", ";").replace("\r", ";");
    }

}
